package org.sbear.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        MultiValueMap <String, HttpCookie> cookie2s = request.getCookies();

        RequestPath path = request.getPath();
        String requestPath = path.toString();

        //这里校验token并拦截除了登录、获取验证码等操作以外的操作。
        //比较特殊的是，这个应用除了获取用户登录信息以外所有其他接口都是登录之前的操作，所以就暂时只拦截这一个了
        if(requestPath.startsWith("/user/info")){
            String token = "";
            MultiValueMap <String, HttpCookie> cookies = request.getCookies();
            List <HttpCookie> list = cookies.get("normal_toke");
            if(list!=null && list.size()>=0){
                HttpCookie httpCookie = list.get(0);
                token = httpCookie.getValue();
            }
            //如果没有token就拦截住
            if(StringUtils.isBlank(token)){
                response.setStatusCode(HttpStatus.MOVED_PERMANENTLY); // 状态码
                String data = "no token,Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
